package com.service;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

import com.dao.TGoodsDAO;
import com.dao.TJinhuoDAO;
import com.dao.TOrderItemDAO;
import com.model.TJinhuo;
import com.model.TOrderItem;
import com.util.Cart;

public class cartService
{
	private TGoodsDAO goodsDAO;
	private TOrderItemDAO orderItemDAO;
	private TJinhuoDAO jinhuoDAO;
	
	public String modiNum(int goodsId,int quantity)
	{
		 try
		 {
		 	Thread.sleep(100);
		 } 
		 catch (InterruptedException e)
		 {
			e.printStackTrace();
		 }
		 
		 int kucun=get_kucun(goodsId);
		 System.out.println(kucun+"&&");
		 if(kucun < quantity)
		 {
			return "kucunbuzu";
		 }
		 
		
		 WebContext ctx = WebContextFactory.get(); 
		 HttpSession session=ctx.getSession();
		 Cart cart=(Cart)session.getAttribute("cart");
		 cart.updateCart(goodsId, quantity);
		 session.setAttribute("cart", cart);
		 return "yes";
	}
	
	public String delGoodsFromCart(int goodsId)
	{
		try
		{
			Thread.sleep(1000);
		} catch (InterruptedException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		 WebContext ctx = WebContextFactory.get(); 
		 HttpSession session=ctx.getSession();
		 Cart cart=(Cart)session.getAttribute("cart");
		 cart.delGoods(goodsId);
		 session.setAttribute("cart", cart);
		 return "yes";
	}
	
	
	public String clearCart()
	{
		try
		{
			Thread.sleep(1000);
		} catch (InterruptedException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 WebContext ctx = WebContextFactory.get(); 
		 HttpSession session=ctx.getSession();
		 Cart cart=(Cart)session.getAttribute("cart");
		 cart.getItems().clear();
		 session.setAttribute("cart", cart);
		 return "yes";
	}
	
	public int get_kucun(int goodsId)
	{
        int j=0;
		String sql="from TJinhuo where goods_id="+goodsId;
		List jinhuoList=jinhuoDAO.getHibernateTemplate().find(sql);
		for(int i=0;i<jinhuoList.size();i++)
		{
			TJinhuo jinhuo=(TJinhuo)jinhuoList.get(i);
			j=j+jinhuo.getShuliang();
		}
		
        int k=0;
		String sql1="from TOrderItem where goodsId="+goodsId;
		List orderItemList=orderItemDAO.getHibernateTemplate().find(sql1);
		for(int i=0;i<orderItemList.size();i++)
		{
			TOrderItem orderItem=(TOrderItem)orderItemList.get(i);
			k=k+orderItem.getGoodsQuantity();
		}
		
		return j-k;
	}

	public TGoodsDAO getGoodsDAO()
	{
		return goodsDAO;
	}

	public void setGoodsDAO(TGoodsDAO goodsDAO)
	{
		this.goodsDAO = goodsDAO;
	}

	public TOrderItemDAO getOrderItemDAO() {
		return orderItemDAO;
	}

	public void setOrderItemDAO(TOrderItemDAO orderItemDAO) {
		this.orderItemDAO = orderItemDAO;
	}

	public TJinhuoDAO getJinhuoDAO() {
		return jinhuoDAO;
	}

	public void setJinhuoDAO(TJinhuoDAO jinhuoDAO) {
		this.jinhuoDAO = jinhuoDAO;
	}

	
}
